<?php

namespace App\Kuafu\Activity\Controller\B;

use App\Exceptions\CustomValidateException;
use App\Kuafu\Activity\Enum\ActivityCodeEnum;
use App\Kuafu\Activity\Enum\ActivityEnum;
use App\Kuafu\Activity\Exceptions\ActivityException;
use App\Kuafu\Activity\Service\ActivityService;
use App\Kuafu\Activity\Validate\ActivityNewValidate;
use App\Kuafu\Activity\Validate\ActivityValidate;
use App\Kuafu\Base\Controller\BaseController;
use App\Kuafu\Shop\Service\ShopService;
use App\Kuafu\User\Exceptions\UserException;
use App\Kuafu\Wechat\Exceptions\WechatException;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use function GuzzleHttp\Promise\all;

class ActivityController extends BaseController
{
    /**
     * @param Request $request
     * @return JsonResponse
     * @throws ActivityException
     * @throws ContainerExceptionInterface
     * @throws CustomValidateException
     * @throws NotFoundExceptionInterface
     * @throws WechatException
     * @throws GuzzleException
     */
    public function create(Request $request): JsonResponse
    {
        $preParams = ActivityNewValidate::createActivityPreValidate($request->all());
        if($preParams->type >= ActivityEnum::TYPE_DAILY_ACTIVITY){
            $validateFunc = "createActivityValidate_{$preParams->type}";
            $params = ActivityNewValidate::{$validateFunc}($preParams->type, $request->all());
            //添加活动
            ActivityService::createNewActivity(
                auth('api')->user()->id,
                $preParams->type,
                $params,
                $request->header('brandId')
            );
        }else{
            $err = ActivityValidate::addActivity($request->all());
            if (strlen($err)) {
                return $this->fail(ActivityCodeEnum::ERR_ACTIVITY_PARAM_VALID, $err);
            }
            if ($request->type == ActivityEnum::TYPE_REGISTRATION) {
                if (!is_array($request->imageList)) {
                    return $this->fail(ActivityCodeEnum::ERR_ACTIVITY_NO_IMAGE,
                        ActivityCodeEnum::CODE_TEXT[ActivityCodeEnum::ERR_ACTIVITY_NO_IMAGE]);
                }
            }

            //添加活动
            ActivityService::createActivity($request->header('brandId'), $request->all(), auth('api')->user()->id);
        }

        return $this->success([]);
    }

    /**
     * 根据活动id获取活动详情
     * @param Request $request
     * @param $id
     * @return JsonResponse
     * @throws UserException
     */
    public function getActivityById(Request $request, $id): JsonResponse
    {
        $id    = (int)$id;
        $valid = ActivityValidate::getActivityById(['id' => $id]);
        if ($valid) {
            return $this->fail(ActivityCodeEnum::ERR_ACTIVITY_PARAM_VALID, $valid);
        }
        $info = ActivityService::getActivityById($this->shopId, $id);

        return $this->success($info);
    }

    /**
     * 获取活动列表
     * @param Request $request
     * @return JsonResponse
     */

    public function getActivityList(Request $request): JsonResponse
    {
        $shopId          = (int)$request->shopId ?: 0;
        $name            = (string)$request->name;
        $type            = (int)$request->get('type', 0);
        $status          = (string)$request->get('status', '');
        $createdUserName = (string)$request->createdUserName;
        $pageSize        = $request->get('pageSize', 20);
        $pageNum         = $request->get('pageNum', 1);
        $shopType        = 0;
        if ($shopId) {
            $shopInfo = ShopService::getShopInfo($shopId);
            $shopType = $shopInfo['type'];
        }
        $data = ActivityService::getActivityList($request->header('brandId'), $name, $type, $status,
            $createdUserName, $shopId, $pageSize, $pageNum, $shopType);
        return $this->success($data);
    }

    /**
     * 删除（软删除）
     * @param Request $request
     * @param $id
     * @return JsonResponse
     * @throws ActivityException
     */
    public function delActivity(Request $request, $id): JsonResponse
    {
        $id    = (int)$id;
        $valid = ActivityValidate::delActivity(['id' => $id]);
        if ($valid) {
            return $this->fail(ActivityCodeEnum::ERR_ACTIVITY_PARAM_VALID, $valid);
        }

        ActivityService::delActivity($id);
        return $this->success();
    }

    /**
     * 根据id修改信息
     * @param Request $request
     * @param $id
     * @return JsonResponse
     * @throws ActivityException
     */
    public function setActivity(Request $request, $id): JsonResponse
    {
        $id    = (int)$id;
        $valid = ActivityValidate::setActivity($request->all() + ['id' => $id]);
        if ($valid) {
            return $this->fail(ActivityCodeEnum::ERR_ACTIVITY_PARAM_VALID, $valid);
        }

        ActivityService::setActivity($id, $request->all());
        return $this->success();
    }

    public function setStatus(Request $request): JsonResponse
    {
        $status = (int)$request->status;
        $id     = (int)$request->id;
        try {
            ActivityService::setStatus($id, $status);
        } catch (Exception $exception) {
            return $this->fail($exception->getCode(), $exception->getMessage());
        }
        return $this->success();
    }


    /**
     * 更新活动
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     * @throws CustomValidateException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function update(Request $request, int $id): JsonResponse
    {
        $params = ActivityNewValidate::updateValidate($request->merge(["id" => $id])->all());
        ActivityService::update($params);
        return $this->success();
    }

    /**
     * 活动管理-私域活动物料素材批量生成
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function materialsGeneration(Request $request, $id): JsonResponse
    {
        $rmsUserId = auth('api')->user()->id;
        ActivityService::materialsGeneration($id, $rmsUserId);
        return $this->success();
    }
}
